package edu.scsu.csci.view;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;

import edu.scsu.csci.IView;
import edu.scsu.csci.context.ViewContext;
import edu.scsu.csci.controller.WebUtils;
import edu.scsu.csci.util.Utilities;

/**
 * <p>	Forwads the request to the specified JSP page. 
 *  
 * @author Maqbool Khan
 * @since jdk 1.5
 * @see
 */
public class JSPView implements IView{
	 
	/** 
	 * <p> Fowards the request to the jsp page.
	 * <p> If any erros are found the request is forward to the error page else otherwise.
	 * 
	 * @see edu.scsu.csci.IView#render(edu.scsu.csci.context.ViewContext)
	 */
	public void render(ViewContext viewContext)throws ViewException{
		try {
			
			String resource = null;
			if(WebUtils.getExecutionErrors() == null || WebUtils.getExecutionErrors().getList().isEmpty()){
				String resourceLocation = Utilities.isNullOrEmpty(viewContext.getResourceLocation()) ? "" : viewContext.getResourceName() + "/";
				resource = resourceLocation + viewContext.getResourceName() ;
			}
			else if(! WebUtils.getExecutionErrors().getList().isEmpty())	{
				String resourceLocation = Utilities.isNullOrEmpty(viewContext.getErrorResourceLocation()) ? "" : viewContext.getErrorResourceLocation() + "/"; 
				resource = resourceLocation + viewContext.getErrorResourceName() ;
			}
			RequestDispatcher rd = viewContext.getRequest().getRequestDispatcher(resource + ".jsp");
			
			if (rd == null){
				throw new ServletException("Can't get RequestDispatcher for '" + viewContext.getResourceName() + "': check that this file exists within your WAR");
			}
			rd.forward(viewContext.getRequest(), viewContext.getResponse());
		}catch (Throwable e) {
			throw new ViewException("Couldn't dispatch to JSP with url '" + viewContext.getResourceLocation() + "/" + viewContext.getResourceName() + "' in InternalResourceView with name '" + viewContext.getResourceName() + "'", e);
		} 
	}
	
}
